<template>
	<view>
		<u-form :model="model" :rules="rules" ref="form" labelPosition="top" labelWidth="auto" :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }">
			<view class="basic-style">
				<view class="basic-title basic-border">基本信息</view>
				<u-form-item label="单据编号" prop="billNo" required>
					<u--input v-model="model.billNo" disabled></u--input>
				</u-form-item>
				<u-form-item label="申请人" prop="proposer" required>
					<h-select-person-input style="width: 100%" disabled v-model="model.proposer" placeholder="请选择申请人"
						border="surround" suffixIcon="arrow-down-fill" :suffixIconStyle="{ color: '#B2B2B2' }"
						objectField="model.proposer"></h-select-person-input>
				</u-form-item>
				<u-form-item label="申请部门" prop="proposerDeptId" required>
					<h-select-depart-input disabled v-model="model.proposerDeptId" :departName="model.proposerDeptText"
						placeholder="请选择部门" border="surround" style="width: 100%" suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }" :title.sync="model.proposerDeptText"></h-select-depart-input>
				</u-form-item>
				<u-form-item label="申请时间" prop="createTime" required>
					<u--input v-model="model.createTime" disabled></u--input>
				</u-form-item>
				<u-form-item label="费用所属团队" prop="teamId" required>
					<h-select-team-input style="width: 100%" disabled v-model="model.teamId" objectField="model.teamId"
						placeholder="请选择费用所属团队" border="surround" :tdlx="3" suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }" @detail="handleTeamChange" isApi="expenseReimbursement"
						@input="teamBack"></h-select-team-input>
				</u-form-item>
				<u-form-item label="申请公司" prop="companyId" required>
					<h-select-company-input style="width: 100%" disabled v-model="model.companyId" border="surround"
						placeholder="请选择公司" suffixIcon="arrow-down-fill" :suffixIconStyle="{ color: '#B2B2B2' }"
						objectField="model.companyId" @input="companyBack"></h-select-company-input>
				</u-form-item>
				<u-form-item label="出差人员" prop="employeeId" required>
					<h-select-person-input isMulti disabled v-model="model.employeeId" style="width: 100%" placeholder="请选择员工"
						border="surround" suffixIcon="arrow-down-fill" :suffixIconStyle="{ color: '#B2B2B2' }"
						objectField="model.employeeId"></h-select-person-input>
				</u-form-item>
				<!-- <u-form-item label="是否外聘人员" prop="isExternalEngagedEmployee" required>
					<h-radio-group v-model="model.isExternalEngagedEmployee" dictName="YES_OR_NO"
						@change="isExternalEngagedEmployeeChange"></h-radio-group>
				</u-form-item>
				<u-form-item label="外聘人员" prop="externalPersonnel">
					<u--input v-model="model.externalPersonnel" placeholder="请输入外聘人员，多人用逗号分隔"
						:disabled="model.isExternalEngagedEmployee === '0'"></u--input>
				</u-form-item> -->
				<u-form-item label="单据类型" prop="billCategory" required>
					<h-radio-group v-model="model.billCategory" disabled dictName="bill_category"></h-radio-group>
				</u-form-item>

				<u-form-item label="费用所属年度" prop="teamYear" v-if="model.teamYear=='2023'">
					<h-select-input-tag disabled style="width: 100%" dictName="tdnd_type" v-model="model.teamYear"
						placeholder="请选择费用所属年度" border="surround" suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"></h-select-input-tag>
				</u-form-item>
				<u-form-item label="本次支付金额(元)" prop="currentPaymentAmount" required>
					<u--input disabled placeholder="请输入本次支付金额" v-model="model.currentPaymentAmount"></u--input>
				</u-form-item>
				<u-form-item label="本次累计冲账金额(元)" prop="chargedAmount">
					<u--input disabled placeholder="请输入本次累计冲账金额" v-model="model.chargedAmount"></u--input>
				</u-form-item>
				<u-form-item label="团队费用类别" prop="teamFeeCategory" required>
					<h-select-input-tag style="width: 100%" dictName="team_fee_category" v-model="model.teamFeeCategory"
						placeholder="请选择团队费用类别" border="surround" suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"></h-select-input-tag>
				</u-form-item>
				<u-form-item label="是否关联项目" prop="isRelProject" required>
					<h-radio-group v-model="model.isRelProject" disabled dictName="YES_OR_NO"
						@change="projectInput"></h-radio-group>
				</u-form-item>
				<u-form-item label="是否使用商务卡" prop="isUseBusinessCard" required>
					<h-radio-group v-model="model.isUseBusinessCard" dictName="YES_OR_NO" disabled></h-radio-group>
				</u-form-item>
				<u-form-item label="出差事由" prop="travelReasons" required>
					<u--textarea v-model="model.travelReasons" disabled :confirm-type="null" maxlength="500" count
						placeholder="请输入出差事由"></u--textarea>
				</u-form-item>
			</view>

			<view class="basic-style">
				<view class="basic-title basic-border">报销详情</view>
				<view class="trip-form-data">
					<u-collapse ref="collapseView1">
						<u-checkbox-group v-model="syncItems" placement="column">
							<u-collapse-item :title="`报销表单${index + 1}`" v-for="(item, index) in tripData" :key="index">
								<view class="checkbox-item space-x-1" @click="handleCheckboxClick(index)">
									<BillFormInfo :isRelProject="isRelProject" formType="trip" :item="item" :index="index" :disabled="true" @copy="handleCopyTripForm"
										@edit="handleEditTripForm" @remove="(item) => handleRemoveTripForm(item)" />
								</view>
							</u-collapse-item>
						</u-checkbox-group>
					</u-collapse>
					<view class="trip-info py-1">
						报销明细费用累计：
						<b>{{ tripTotal }}</b>
						元 （注：本次报销实际支付金额为报销明细费用累计。）
					</view>
				</view>
				<u-popup :round="10" mode="bottom" :closeOnClickOverlay="false" :show="showTripModal"
					@close="closeTripModal" @open="openTripModal">
					<BillForm ref="tripForm" :index="index" :teamId="model.teamId" :companyId="model.companyId" :disabled="true"
						:isRelProject="isRelProject" @submit="handleTripSubmit" @close="showTripModal = false" />
				</u-popup>
			</view>

			<view class="basic-style">
				<view class="basic-title basic-border">自驾公里数补助明细</view>
				<view class="trip-form-data">
					<u-collapse ref="collapseView2">
						<u-collapse-item :title="`自驾公里数补助表单${index + 1}`" v-for="(item, index) in driveData"
							:key="index">
							<BillFormInfo :isRelProject="isRelProject" formType="drive" :item="item" :isBtn="true" :index="index" @edit="handleEditDriveForm"
								@remove="handleRemoveDriveForm" @copy="handleCopyDriveForm" />
						</u-collapse-item>
					</u-collapse>
					<view class="trip-info py-1">
						自驾公里数补助明细费用累计：
						<b>{{ driveTotal }}</b>
						元 （注：自驾公里数补助累计不计入本次报销金额，使用油卡和定额提现方式兑现。）
					</view>
				</view>
			</view>

			<view class="basic-style">
				<view class="basic-title basic-border">结算信息</view>
				<view class="trip-form-data">
					<u-form-item label="冲账单据类型" prop="relBillType">
						<h-select-input-tag class="w-100" v-model="model.relBillType"
							placeholder="请选择冲账单据类型" disabled border="surround" suffixIcon="arrow-down-fill"
							:suffixIconStyle="{ color: '#B2B2B2' }" dictName="bill_type"
						></h-select-input-tag>
					</u-form-item>
					<view v-if="model.relBillType==1">
						<view class="trip-form-data">
							<u-collapse ref="collapseView3">
								<u-collapse-item :title="`借款单单据${index + 1}`" v-for="(item, index) in model.chargedInfoList"
									:key="index">
									<LoanBillFormInfo :item="item" :index="index" @edit="handleEditLoanForm" :isBtn="true"
										@remove="handleRemoveLoanForm" />
								</u-collapse-item>
							</u-collapse>
						</view>
						<u-popup :round="10" mode="bottom" :closeOnClickOverlay="false" :show="showLoanModal"
							@close="closeLoanModal" @open="openLoanModal">
							<LoanBillForm :teamId="model.teamId" :companyId="model.companyId" ref="LoanForm" :index="index" @submit="handleLoanSubmit" @close="showLoanModal = false" />
						</u-popup>
					</view>
					<u-form-item label="结算方式" prop="settleType" required>
						<h-select-input-tag class="w-100" v-model="model.settleType" disabled objectField="model.settleType"
							placeholder="请选择结算方式" border="surround" suffixIcon="arrow-down-fill"
							:suffixIconStyle="{ color: '#B2B2B2' }" dictName="settle_type_all"
							@change="handleSettleTypeChange"></h-select-input-tag>
					</u-form-item>
					<template v-if="model.settleType === '0'">
						<u-form-item label="收款员工" prop="payeeName" required>
							<h-select-person-input style="width: 100%" v-model="model.payeeName" disabled placeholder="请选择收款员工"
								border="surround" suffixIcon="arrow-down-fill" :suffixIconStyle="{ color: '#B2B2B2' }"
								objectField="model.payeeName" @input="selectAccountName"></h-select-person-input>
						</u-form-item>
						<u-form-item label="开户行联行号" prop="cnapsCode" required>
							<u--input placeholder="请输入开户行联行号" v-model="model.cnapsCode" disabled></u--input>
						</u-form-item>
						<u-form-item label="收款开户行" prop="bankName" required>
							<u--input placeholder="请输入收款开户行" disabled v-model="model.bankName"></u--input>
						</u-form-item>
						<u-form-item label="收款账号" prop="accountNo" required>
							<u--input placeholder="请输入收款账号" disabled v-model="model.accountNo" :maxlength="32"></u--input>
						</u-form-item>
					</template>
					<template v-if="model.settleType === '2'">
						<u-form-item label="关联借款申请" prop="loanBillId" required>
							<h-select-borrowbill-input-popup :disabled="!model.companyId && !model.teamId" class="w-100"
								:checkStatus="2" :teamId="model.teamId" disabled :companyId="model.companyId" :settleAccounts="0"
								:proposer="model.proposer" v-model="model.loanBillId" placeholder="请选择关联借款申请"
								border="surround" suffixIcon="arrow-down-fill" :suffixIconStyle="{ color: '#B2B2B2' }"
								@change="handleLoanBillChange"></h-select-borrowbill-input-popup>
						</u-form-item>
						<u-form-item label="未还金额(元)" prop="outstandingAmount">
							<u--input disabled placeholder="请输入未还金额" v-model="model.outstandingAmount"></u--input>
						</u-form-item>
						<u-form-item label="支付金额(元)" prop="paymentAmount">
							<u--input disabled placeholder="请输入支付金额" v-model="model.paymentAmount"></u--input>
						</u-form-item>
					</template>
				</view>
			</view>

			<view class="basic-style">
				<view class="basic-title basic-border">附件信息</view>
				<view class="py-1 space-y-1" style="width: 100%">
					<file-list v-if="model.attachments" v-model="model.attachments"></file-list>
				</view>
			</view>

			<view class="space-x-1 px-1 btn_position">
				<backButton  @onSubmit="onSubmit" :nodeObj="nodeObj" :model="dataForm" :resultObj="resultObj"></backButton>
			</view>
			<view style="height: 100rpx"></view>
		</u-form>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import moment from 'moment'
	import {
		getProcessTaskTransInfo // 流程流转
	} from '@/api/index.js'
	import http from '@/utils/request'
	import backButton from '@/components/backButton.vue'
	import {
		gainBillNo,
		add,
		info,
		edit,
		erpFinanceTravelReimbursementDetail
	} from '@/api/finance/ErpFinanceTravelReimbursementBillForm'
	import {
		filterMultiDictText,
		initDictOptions
	} from '@/utils/JDictSelectUtil.js'
	import fileList from '@/pages/synergy/components/fileList.vue'
	import BillForm from '@/pages/finance/components/BillForm.vue'
	import BillFormInfo from '@/pages/finance/components/BillFormInfo.vue'
	import LoanBillForm from '@/pages/finance/components/LoanBillForm.vue'
	import LoanBillFormInfo from '@/pages/finance/components/LoanBillFormInfo.vue'
	import Decimal from 'decimal.js'
	export default {
		name: 'ErpFinanceTravelReimbursementBillFormBack',
		components: {
			fileList,
			BillForm,
			BillFormInfo,
			LoanBillForm,
			LoanBillFormInfo,
			backButton
		},
		data() {
			return {
				dictOptions: {},
				isReset: false,
				companyIdBackups: '',
				teamIdBackups: '',
				backUpCompanyId: '',
				backUpTeamId: '',
				backUpIsRelProject: '',
				resetKey: '',
				syncItems: [],
				basicForm: {},
				index: null,
				showTripModal: false,
				showDriveModal: false,
				showLoanModal: false,
				confirmModal: false,
				isSubmit: false,
				id: '',
				nodeObj: {},
				tabvalue: '',
				dataForm: {},
				resultObj: {},
				model: {
					// 基本信息 - 公用
					bpmBizTitle: '',
					billNo: '',
					checkStatus: 0,
					applyOilFilling: '0',
					chargedInfoList: [],
					proposer: '',
					proposerDeptId: '',
					createTime: '',
					companyId: null,
					// 基本信息 - 非公用
					employeeId: '',
					// isExternalEngagedEmployee: '0',
					// externalPersonnel: '',
					billCategory: '',
					teamId: null,
					// teamYear: '',
					teamFeeCategory: '',
					isRelProject: '1',
					travelReasons: '',
					isUseBusinessCard: '',
					settleType: '',
					currentPaymentAmount:'',
					payeeName: '',
					bankName: '',
					cnapsCode: '',
					accountNo: '',
					loanBillId_dictText: '',
					outstandingAmount: '',
					paymentAmount: '',
					relBillType: '',
					// 附件
					attachments: null,
				},
				tripData: [],
				driveData: [],
				rules: {
					billNo: [{
						required: true,
						message: '请输入单据编号!',
						trigger: ['blur', 'change'],
					}, ],
					proposerDeptId: [{
						required: true,
						message: '请选择申请部门!',
						trigger: ['blur', 'change'],
					}, ],
					proposer: [{
						required: true,
						message: '请选择申请人!',
						trigger: ['blur', 'change'],
					}, ],
					createTime: [{
						required: true,
						message: '请选择申请时间!',
						trigger: ['blur', 'change'],
					}, ],
					// isExternalEngagedEmployee: [{
					// 	required: true,
					// 	message: '请选择是否外聘人员!',
					// 	trigger: ['blur', 'change']
					// }],
					isRelProject: [{
						required: true,
						message: '请选择是否关联项目!',
						trigger: ['blur', 'change']
					}],
					isUseBusinessCard: [{
						required: true,
						message: '请选择是否使用商务卡!',
						trigger: ['blur', 'change'],
					}],
					travelReasons: [{
						required: true,
						message: '请填写出差事由!',
						trigger: ['blur', 'change']
					}],
					settleType: [{
						required: true,
						message: '请选择结算方式!',
						trigger: ['blur', 'change']
					}],
					payeeName: [{
						required: true,
						message: '请选择收款员工!',
						trigger: ['blur', 'change']
					}],
					bankName: [{
						required: true,
						message: '请输入收款开户行!',
						trigger: ['blur', 'change']
					}],
					cnapsCode: [{
						required: true,
						message: '请输入开户行联行号!',
						trigger: ['blur', 'change']
					}],
					accountNo: [{
						required: true,
						message: '请输入正确的银行卡号!',
						trigger: ['blur', 'change']
					}],
					loanBillId: [{
						required: true,
						message: '请选择关联借款单!',
						trigger: ['blur', 'change']
					}],
					billCategory: [{
						required: true,
						message: '请选择单据类型!',
						trigger: ['blur', 'change']
					}],
					teamId: [{
						required: true,
						message: '请选择费用所属团队!',
						trigger: ['blur', 'change']
					}],
					currentPaymentAmount: [
						{required: true, type: 'number', message: '请输入本次支付金额!', trigger: ['blur', 'change']},
						{ required: true, pattern: /^(([0-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '金额不能小于零!', trigger: ['blur', 'change'] }
					],
					companyId: [{
						required: true,
						message: '请选择所属公司!',
						trigger: ['blur', 'change']
					}],
					teamFeeCategory: [{
						required: true,
						message: '请选择团队费用类别!',
						trigger: ['blur', 'change']
					}],
					employeeId: [{
						required: true,
						message: '请选择出差人员!',
						trigger: ['blur', 'change']
					}],
				},
				// 代码生成后需手动设置流程编码
				flowCode: 'onl_erp_finance_travel_reimbursement_bill',
				formUrl: '/erp/finance/travel/modules/ErpFinanceTravelReimbursementBillForm',
				formUrlMobile: '/pages/synergy/erpFinanceTravelReimbursementBillList',
				processId: '1522474849156538369',
				beanName: 'erpFinanceTravelReimbursementBillServiceImpl',
			}
		},
		provide() {
			return {
				dictOptions: this.dictOptions,
			}
		},
		onLoad(options) {
			this.initDicts()
			this.dataForm = JSON.parse(decodeURIComponent(options.item))
			
			var that = this
			// #ifdef APP-NVUE
			var eventChannel = this.$scope.eventChannel // 兼容APP-NVUE
			// #endif
			// #ifndef APP-NVUE
			var eventChannel = this.getOpenerEventChannel()
			// #endif
			// 监听sendMessage事件，获取上一页面通过eventChannel传送到当前页面的数据
			eventChannel.on('sendMessage', function (data) {
			  that.tabvalue = data.tabvalue
			  that.nodeObj = JSON.parse(decodeURIComponent(data.nodeObj))
			  // that.loadData(that.nodeObj.dataId)
				that.id = that.nodeObj.dataId
				that.initInfo()
				that.initChildData(that.id, '1')
				that.initChildData(that.id, '2')
				that.getProcessTaskTrans(that.dataForm.id)
			})
		},
		computed: {
			...mapState(['userInfo']),
			isRelProject() {
				return this.model.isRelProject === '1'
			},
			tripTotal() {
				let amount = this.tripData.reduce((total, item) => total + Number(item.amount), 0).toFixed(2)
				this.getCurrentPaymentAmount(amount, this.model.chargedAmount)
				return amount
			},
			driveTotal() {
				return this.driveData.reduce((total, item) => total + Number(item.amount), 0).toFixed(2)
			},
		},
		methods: {
			// 计算本次支付金额
			getCurrentPaymentAmount(reimbursementAmount = 0, chargedAmount = 0) {
			  // 本次支付金额=报销明细费用累计-本次累计冲账金额(元)，最小为0
			  reimbursementAmount = new Decimal(reimbursementAmount || 0) // 报销明细费用累计
			  chargedAmount = new Decimal(chargedAmount || 0) // 本次累计冲账金额
			  let currentPaymentAmount = reimbursementAmount.sub(chargedAmount).toNumber()
			  this.$set(this.model, 'currentPaymentAmount', currentPaymentAmount)
			},
			// 查询流程流转信息 -- 获取下一节点信息
			getProcessTaskTrans(taskId){
				getProcessTaskTransInfo({ taskId }).then(res => {
					if(res.success){
						this.resultObj = res.result
					} else {
						this.$refs.uToast.show({
							message: res.message,
							type: 'error'
						})
					}
				}).catch(err => {
					console.log(err);
				})
			},
			//支付金额数据判断
			handlePayAmount(){
				let model=this.model;
				let currentPaymentAmount=model.currentPaymentAmount
				let data=this.tripData;
				let amount=0;
				data.forEach(item=>{
					amount+=Number(item.amount);
				})
				amount=amount.toFixed(2);
				if( parseFloat(currentPaymentAmount) > parseFloat(amount) ){
					return true;
				}
				return false;
			},
			//支付金额数据判断是否大于报销后的冲账剩余金额
			handlePayAndChargedAmount(){
				let model=this.model;
				let currentPaymentAmount=model.currentPaymentAmount
				let chargedAmount=model.chargedAmount
				let data=this.tripData;
				let amount=0;
				data.forEach(item=>{
					amount+=Number(item.amount);
				})
				let unChargedAmount=(amount-chargedAmount).toFixed(2)
				if( parseFloat(currentPaymentAmount) > parseFloat(unChargedAmount)){
					return true;
				}
				return false;
			},
			collapseView1Init() {
			  setTimeout(() => {
				this.$refs.collapseView1.init()
			  }, 500)
			},
			collapseView2Init() {
			  setTimeout(() => {
				this.$refs.collapseView2.init()
			  }, 500)
			},
			collapseView3Init() {
			  setTimeout(() => {
				this.$refs.collapseView3.init()
			  }, 500)
			},
			teamBack(item) {
				//判断不为空
				if (!!this.model.teamId && item) {
					//判断团队是否变化
					if (this.teamIdBackups !== item.id) {
						if ((this.model.isRelProject == 1 && this.tripData.length > 0) || this.driveData.length > 0) {
							this.tdnd = item.tdnd
							const that = this
							uni.showModal({
								title: '是否确认',
								content: '是否确认切换费用所属团队，此操作将会清空报销详情明细和自驾公里数补助明细中已填写的所有信息？',
								success: async (res) => {
									if (res.confirm) {
										//确认后进行改变
										that.teamIdBackups = that.model.teamId
										// that.model.teamYear = that.tdnd
										that.tripData = []
										that.driveData = []
										//清除借款单字段
										that.$set(that.model, 'loanBillId', null)
										that.$set(that.model, 'outstandingAmount', null)
										that.$set(that.model, 'paymentAmount', null)
										that.$refs.form.clearValidate('loanBillId')
										//清空金额
										that.$set(that.model, 'reimbursementAmount', 0)
										that.getCurrentPaymentAmount(that.model.reimbursementAmount, that.model.chargedAmount)
										that.$set(that.model, 'kilometresAmount', 0)
										that.$set(that.model, 'thisAmount', 0)
									} else {
										that.model.teamId = that.teamIdBackups
									}
								},
							})
						} else {
							const that = this
							this.teamIdBackups = item.id
							// this.model.teamYear = item.tdnd
							that.tripData = []
							that.driveData = []
							//清除借款单字段
							this.$set(this.model, 'loanBillId', null)
							this.$set(this.model, 'outstandingAmount', null)
							this.$set(this.model, 'paymentAmount', null)
							this.$refs.form.clearValidate('loanBillId')
							//清空金额
							this.$set(that.model, 'reimbursementAmount', 0)
							this.getCurrentPaymentAmount(this.model.reimbursementAmount, this.model.chargedAmount)
							this.$set(that.model, 'kilometresAmount', 0)
							this.$set(that.model, 'thisAmount', 0)
						}
					}
				}
			},
			companyBack(item) {
				//判断不为空
				if (!!this.model.companyId && item) {
					//判断公司是否变化
					if (this.companyIdBackups !== item.id) {
						const that = this
						if ((this.model.isRelProject == 1 && this.tripData.length > 0) || this.driveData.length > 0) {
							uni.showModal({
								title: '是否确认',
								content: '是否确认切换申请公司，此操作将会清空报销详情明细和自驾公里数补助明细中已填写的所有信息？',
								success: async (res) => {
									if (res.confirm) {
										//确认后进行改变
										that.companyIdBackups = that.model.companyId
										that.tripData = []
										that.driveData = []
										//清除借款单字段
										that.$set(that.model, 'loanBillId', null)
										that.$set(that.model, 'outstandingAmount', null)
										that.$set(that.model, 'paymentAmount', null)
										that.$refs.form.clearValidate('loanBillId')
										//清空金额
										that.$set(that.model, 'reimbursementAmount', 0)
										that.getCurrentPaymentAmount(that.model.reimbursementAmount, that.model.chargedAmount)
										that.$set(that.model, 'kilometresAmount', 0)
										that.$set(that.model, 'thisAmount', 0)
									} else {
										that.model.companyId = that.companyIdBackups
									}
								},
							})
						} else {
							this.companyIdBackups = item.id
							that.tripData = []
							that.driveData = []
							//清除借款单字段
							this.$set(this.model, 'loanBillId', null)
							this.$set(this.model, 'outstandingAmount', null)
							this.$set(this.model, 'paymentAmount', null)
							this.$refs.form.clearValidate('loanBillId')
							//清空金额projectInput
							this.$set(that.model, 'reimbursementAmount', 0)
							this.getCurrentPaymentAmount(this.model.reimbursementAmount, this.model.chargedAmount)
							this.$set(that.model, 'kilometresAmount', 0)
							this.$set(that.model, 'thisAmount', 0)
						}
					}
				}
			},
			projectInput(data) {
				if (this.tripData.length > 0 || this.driveData.length > 0) {
					uni.showModal({
						title: '是否确认',
						content: '你确定要切换是否关联项目？如果切换则会清除报销详情和自驾公里数补助明细中已填写的所有信息？',
						success: async (res) => {
							if (res.confirm) {
								this.tripData = []
								this.driveData = []
							} else {
								if (this.model.isRelProject == '0') {
									this.model.isRelProject = '1'
								} else {
									this.model.isRelProject = '0'
								}
							}
						},
					})
				}
			},
			initDicts() {
				initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
					if (res.success) {
						this.$set(this.dictOptions, 'teamManager', res.result)
					}
				})
				initDictOptions('erp_finance_loan_bill,bill_no,id').then((res) => {
					if (res.success) {
						this.$set(this.dictOptions, 'relLoanBillId', res.result)
					}
				})
				initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
					if (res.success) {
						this.$set(this.dictOptions, 'teamId', res.result)
					}
				})
				initDictOptions('erp_omc_project,project_name,id').then((res) => {
					if (res.success) {
						this.$set(this.dictOptions, 'projectId', res.result)
					}
				})
				initDictOptions('erp_omc_project_task,category_name,id').then((res) => {
					if (res.success) {
						this.$set(this.dictOptions, 'taskId', res.result)
					}
				})
				initDictOptions('yjgsnd').then((res) => {
					if (res.success) {
						this.$set(this.dictOptions, 'attributionYear', res.result)
					}
				})
				initDictOptions('reimbursement_content').then((res) => {
					if (res.success) {
						this.$set(this.dictOptions, 'feeType', res.result)
					}
				})
				initDictOptions('transportation').then((res) => {
					if (res.success) {
						this.$set(this.dictOptions, 'transportMode', res.result)
					}
				})
				initDictOptions('invoice_type').then((res) => {
					if (res.success) {
						this.$set(this.dictOptions, 'isSpecial', res.result)
					}
				})
				// initDictOptions('tdnd_type').then((res) => {
				// 	if (res.success) {
				// 		this.$set(this.dictOptions, 'teamYear', res.result)
				// 	}
				// })
				initDictOptions('erp_employee_file,name,id').then((res) => {
					if (res.success) {
						this.$set(this.dictOptions, 'subsidyProposer', res.result)
					}
				})
				initDictOptions('expense_account').then((res) => {
					if (res.success) {
						this.$set(this.dictOptions, 'selfDriving', res.result)
					}
				})
				initDictOptions('traffic').then((res) => {
					if (res.success) {
						this.$set(this.dictOptions, 'selfDrivingMode', res.result)
					}
				})
				initDictOptions('subsidy').then((res) => {
					if (res.success) {
						this.$set(this.dictOptions, 'subsidyUnitPrice', res.result)
					}
				})
			},
			/**
			 * 选择关联借款单申请
			 */
			handleLoanBillChange(res) {
				let amount = new Decimal(res.amount).sub(
					new Decimal(res.repaymentAmount + res.travelReimbursementAmount + res.expenseReimbursementAmount),
				)
				this.model.outstandingAmount = amount.toNumber().toFixed(2)
				if (new Decimal(this.tripTotal).toNumber() > new Decimal(this.model.outstandingAmount).toNumber()) {
					let amount = new Decimal(this.tripTotal).sub(new Decimal(this.model.outstandingAmount))
					this.model.paymentAmount = amount.toNumber().toFixed(2)
				} else {
					this.model.paymentAmount = 0
				}
			},
			handleSettleTypeChange(val) {
				if (val === '0') {
					this.$set(this.model, 'loanBillId', null)
					this.$set(this.model, 'outstandingAmount', null)
					this.$set(this.model, 'paymentAmount', null)
					// this.model.accountName = this.userInfo?.employee?.name || ''
					// this.model.bankName = this.userInfo?.employee?.bankName || ''
					// this.model.cnapsCode = this.userInfo?.employee?.cnapsCode || ''
					// this.model.accountNo = this.userInfo?.employee?.bankCard || ''
					return
				} else if (val === '2') {
					this.$set(this.model, 'accountName', null)
					this.$set(this.model, 'bankName', null)
					this.$set(this.model, 'cnapsCode', null)
					this.$set(this.model, 'accountNo', null)
					return
				} else {
					this.$set(this.model, 'loanBillId', null)
					this.$set(this.model, 'outstandingAmount', null)
					this.$set(this.model, 'paymentAmount', null)
					this.$set(this.model, 'accountName', null)
					this.$set(this.model, 'bankName', null)
					this.$set(this.model, 'cnapsCode', null)
					this.$set(this.model, 'accountNo', null)
				}
			},
			// 选择收款员工
			selectAccountName () {
				let payeeName = this.model.payeeName
				http.get('/api/erp/files/employee/erpEmployeeFile/queryFileById',{id:payeeName}).then(res => {
					if (res.success) {
						this.$set(this.model, 'bankName', res.result.bankName);
						this.$set(this.model, 'cnapsCode', res.result.cnapsCode);
						this.$set(this.model, 'accountNo', res.result.bankCard);
					}
				})
			},
			handleSyncInfo() {
				const self = this;
				if (self.syncItems.length) {
					uni.showModal({
						content: '是否同步选中数据？',
						success: (res) => {
							if (res.confirm) {
								self.syncItems.forEach((index) => {
									let item = JSON.parse(JSON.stringify(self.tripData[index]))
									self.$set(item, 'detailType', '2')
									self.$set(item, 'feeType', null)
									self.$set(item, 'transportMode', null)
									self.$set(item, 'isSpecial', null)
									self.$set(item, 'amount', null)
									self.$set(item, 'taxation', null)
									self.$set(item, 'untaxedAmount', null)
									self.$set(item, 'remark', null)
									self.driveData.push({
										...item,
									})
								})
								self.$u.toast('同步成功！')
							}
						},
					})
				} else {
					self.$u.toast('请选择一条记录！')
				}
			},
			handleCheckboxClick(i) {
				const index = this.syncItems.indexOf(i)
				if (~index) {
					this.syncItems.splice(index, 1)
				} else {
					this.syncItems.push(i)
				}
			},
			// 地址显示
			getAddress(areaCode) {
				var arr = areaCode.split(',')
				if (arr.length === 1) {
					arr.length = 0
					const code1 = areaCode.slice(0, 2)
					const code2 = areaCode.slice(2, 4)
					const code3 = areaCode.slice(4, 6)
					arr.push(code1)
					arr.push(code1 + code2)
					arr.push(code1 + code2 + code3)
					arr = arr.join(',')
				} else {
					arr = areaCode
				}
				return arr
			},
			reSetAreaCode(item) {
				let departurePlace = this.getAddress(item.departurePlace);
				let targetPlace = this.getAddress(item.targetPlace);
				this.$set(item, 'departurePlace', departurePlace)
				this.$set(item, 'targetPlace', targetPlace)
			},
			handleCopyTripForm([item, index]) {
				this.tripData.push({
					...item,
				})
				this.collapseView1Init()
				this.$u.toast('复制成功')
			},
			handleCopyDriveForm([item, index]) {
				this.driveData.push({
					...item,
				})
				this.collapseView2Init()
				this.$u.toast('复制成功')
			},
			handleEditTripForm([item, index]) {
				// this.reSetAreaCode(item)
				this.basicForm = {
					...item
				}
				this.index = index
				this.showTripModal = true
				this.collapseView1Init()
				this.$nextTick(() => {
					this.$refs.tripForm.lxChangeInit(item.isSpecial)
				})
			},
			handleRemoveTripForm(item) {
				this.tripData = this.tripData.filter((i) => i !== item)
				this.collapseView1Init()
			},
			handleEditDriveForm([item, index]) {
				// this.reSetAreaCode(item)
				this.basicForm = {
					...item
				}
				this.index = index
				this.showDriveModal = true
				this.collapseView2Init()
			},
			handleRemoveDriveForm(item) {
				this.driveData = this.driveData.filter((i) => i !== item)
				this.collapseView2Init()
			},
			handleEditLoanForm([item, index]) {
				// this.reSetAreaCode(item)
				this.basicForm = {
					...item
				}
				this.index = index
				this.showLoanModal = true
				this.collapseView13Init()
			},
			handleRemoveLoanForm(item) {
				this.model.chargedInfoList = this.model.chargedInfoList.filter((i) => i !== item)
				// 计算总金额
				this.handelCharedAmount()
				this.collapseView3Init()
			},
			// 获取单据编号
			async initBillNo() {
				const res = await gainBillNo({
					proposer: this.userInfo.empId
				})
				this.model.billNo = res.result
				// this.model.bpmBizTitle = this.userInfo.empName + '-' + this.model.billNo //标题
			},
			// 初始化新增需要的数据
			initForm() {
				this.model.proposer = this.userInfo.empId //当前登录人
				this.model.proposerDeptId = this.userInfo.deptId //当前登录人部门
				this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
				// this.model.payee = this.userInfo.empId //领款人
				this.$set(this.model, 'bankName', this.userInfo?.employee?.bankName) //开户行
				this.$set(this.model, 'cnapsCode', this.userInfo?.employee?.cnapsCode) //开户行
				this.$set(this.model, 'bankAccountNo', this.userInfo?.employee?.bankCard) //银行卡号
			},
			async initChildData(billId, detailType) {
				const response = await erpFinanceTravelReimbursementDetail({
					billId,
					detailType
				})
				const data = response?.result || {}
				if (detailType == '1') {
					this.tripData = data
					this.collapseView1Init()
				} else {
					this.driveData = data
					this.collapseView2Init()
				}
			},
			async initInfo() {
				const response = await info({
					id: this.id
				})
				const data = await response?.result || {}
				this.model = await Object.assign({}, data)
				if (this.model.teamId) {
					this.teamIdBackups = this.model.teamId
				}
				if (this.model.companyId) {
					this.companyIdBackups = this.model.companyId
				}
			},
			isExternalEngagedEmployeeChange(val) {
				if (val === '0') {
					this.model.externalPersonnel = ''
				}
			},
			validateForm() {
				return this.$refs.form.validate().then(() => {
					const index = this.driveData.findIndex((item) => !item.startMileage)
					if (~index) {
						return Promise.reject(`请完善自驾公里数补助明细中序号为【${index}】的明细信息！`)
					}
					return Promise.resolve()
				})
			},
			handleTeamChange(item) {
				// this.model.teamYear = item.tdnd
			},
			validateCT() {
				if (!this.model.companyId) {
					uni.showToast({
						title: '请选择申请公司',
						icon: 'none',
					})
					return false
				}
				if (!this.model.teamId) {
					uni.showToast({
						title: '请选择费用所属团队',
						icon: 'none',
					})
					return false
				}
				return true
			},
			addTrip() {
				if (this.validateCT()) {
					this.index = null
					this.showTripModal = true
					this.$nextTick(() => {
						this.$refs.tripForm.lxChangeInit()
					})
				}
			},
			addDive() {
				if (this.validateCT()) {
					this.index = null
					this.showDriveModal = true
				}
			},
			addLoan() {
				this.index = null
				this.showLoanModal = true
			},
			closeTripModal() {
				this.basicForm = {}
				this.$refs.tripForm.reset()
				this.index = null
			},
			openTripModal() {
				this.$refs.tripForm.basicForm = this.basicForm
			},
			closeDriveModal() {
				this.basicForm = {}
				this.$refs.driveForm.reset()
				this.index = null
			},
			openDriveModal() {
				this.$refs.driveForm.basicForm = this.basicForm
			},
			closeLoanModal() {
				this.basicForm = {}
				this.$refs.LoanForm.reset()
				this.index = null
			},
			openLoanModal() {
				this.$refs.LoanForm.basicForm = this.basicForm
			},
			/**
			 * 报销新增点击确认
			 */
			handleTripSubmit([data, index]) {
				this.showTripModal = false
				if (typeof index === 'number') {
					this.$set(this.tripData, index, {
						...data
					})
				} else {
					this.tripData.push(data)
				}
				this.collapseView1Init()
				if (this.model.settleType == 2) {
				  if (new Decimal(this.tripTotal).toNumber() > new Decimal(this.model.outstandingAmount).toNumber()) {
					let amount = new Decimal(this.tripTotal).sub(new Decimal(this.model.outstandingAmount))
					this.model.paymentAmount = amount.toNumber().toFixed(2)
				  } else {
					this.model.paymentAmount = 0
				  }
				}
			},
			/**
			 * 报销新增点击确认
			 */
			handleDriveSubmit([data, index]) {
				this.showDriveModal = false
				if (typeof index === 'number') {
					this.$set(this.driveData, index, {
						...data
					})
				} else {
					this.driveData.push(data)
				}
				this.collapseView2Init()
			},
			/**
			 * 报销新增点击确认
			 */
			handleLoanSubmit([data, index]) {
				this.showLoanModal = false
				if (typeof index === 'number') {
					this.$set(this.model.chargedInfoList, index, {
						...data
					})
				} else {
					this.model.chargedInfoList.push(data)
				}
				this.$refs.LoanForm.dataSource = this.model.chargedInfoList
				// 计算总金额
				this.handelCharedAmount()
				this.collapseView3Init()
			},
			handelCharedAmount(){
				let chargedAmount = 0
				this.model.chargedInfoList.forEach(item=>{
					chargedAmount+=item.chargedAmount;
				})
				this.model.chargedAmount =  chargedAmount.toFixed(2)
				this.getCurrentPaymentAmount(this.model.reimbursementAmount, this.model.chargedAmount)
			},
			/**
			 * 过滤对象中的key返回一个新的对象
			 * @param {Object} obj 要过滤的对象
			 * @param {Array} keys 要过滤的key
			 */
			filterOjbectKeys(obj, keys) {
				const result = {}
				const objKeys = Object.keys(obj).filter((item) => keys.includes(item))
				objKeys.forEach((key) => {
					result[key] = obj[key]
				})
				return result
			},
			// 提交流程成功
			onOk() {
				this.$refs.uToast.show({
					message: '提交成功',
					type: 'success',
					complete() {
						if (getCurrentPages().length > 1) {
							uni.navigateBack()
						} else {
							uni.reLaunch({
								url: '/pages/home/home',
							})
						}
					},
				})
			},
			getCreateTime() {
				let createTime = this.model.createTime
				let date = createTime.substring(0, 10)
				return date.substring(0, 4) + '年' + date.substring(5, 7) + '月' + date.substring(8, 10) + '日'
			},
			setBpmBizTitle() {
				const that = this
				let teamName = filterMultiDictText(this.dictOptions['teamManager'], that.model.teamId + '')
				let createTime = this.getCreateTime(),
					totalMoney = new Decimal(this.tripTotal).toNumber();
				//迭代16.7 取费用所属团队-申请人-申请日期（年月日）-金额（取报销明细费用累计）
				that.model.bpmBizTitle =
					(teamName ? teamName + '-' : '') + that.userInfo?.employee?.name + '-' + createTime + (totalMoney? '-' + totalMoney:'0.00') //标题
			},
			dataCheck() {
				let str = ''
				for (let a = 0; a < this.driveData.length; a++) {
					const item = this.driveData[a]
					if (!item.startMileage) {
						str = str + (a + 1) + '，'
					}
				}
				if (str) {
					str = str.substr(0, str.length - 1)
					this.$refs.uToast.show({
						message: '请完善自驾公里数补助明细中序号为【' + str + '】的明细信息！',
						type: 'error',
					})
					return
				}
			},
			areaCodeFormat(areaCode) {
				let fCode = areaCode,
					arr = areaCode.split(','),
					len = arr.length
				if (len > 1) {
					fCode = arr[len - 1]
				}
				return fCode
			},
			async onSubmit() {
				this.dataCheck()
				await this.validateForm()
				if((this.model.relBillType=='1' || this.model.relBillType=='2') && this.model.chargedInfoList.length==0){
					this.$refs.uToast.show({
						message: '请填写冲账信息',
						type: 'default',
					})
					return ;
				}
				if(this.handlePayAmount()){
					this.$refs.uToast.show({
						message: '本次冲账金额不能大于报销金额',
						type: 'error',
					})
					return ;
				}
				if(this.handlePayAndChargedAmount()){
					this.$refs.uToast.show({
						message: '本次支付金额不能大于报销金额冲账后的剩余金额',
						type: 'error',
					})
					return ;
				}
				this.setBpmBizTitle()
				let url = ''
				if (!this.model.id) {
					url = await add
				} else {
					url = await edit
				}
				try {
					const _tripData = JSON.parse(JSON.stringify(this.tripData))
					const _driveData = JSON.parse(JSON.stringify(this.driveData))
					const response = await url({
						...this.model,
						reimbursementAmount: new Decimal(this.tripTotal || 0).toNumber().toFixed(2),
						kilometresAmount: new Decimal(this.driveTotal || 0).toNumber().toFixed(),
						thisAmount: new Decimal(this.tripTotal || 0)
							.add(new Decimal(this.driveTotal || 0))
							.toNumber()
							.toFixed(2),
						travelDetail: _tripData.map((i, index) => {
							// i.targetPlace = this.areaCodeFormat(i.targetPlace)
							// i.departurePlace = this.areaCodeFormat(i.departurePlace) // 兼容PC地址回显
							return {
								key: index,
								detailType: 1,
								...this.filterOjbectKeys(i, [
									'detailType',
									'taxation',
									'amount',
									'setOutTime',
									'backTime',
									'startMileage',
									'endMileage',
									'oilCard',
									'subsidyProposer',
									'projectId',
									'projectCode',
									'attributionYear',
									'taskId',
									'taskDescription',
									'days',
									'feeType',
									'transportMode',
									'isSpecial',
									'untaxedAmount',
									'remark',
									'departurePlace',
									'targetPlace',
									'taxRate',
									'key',
								]),
							}
						}),
						reimbursementDetail: _driveData.map((i, index) => {
							// i.targetPlace = this.areaCodeFormat(i.targetPlace)
							// i.departurePlace = this.areaCodeFormat(i.departurePlace) // 兼容PC地址回显
							return {
								key: index,
								detailType: 2,
								...this.filterOjbectKeys(i, [
									'detailType',
									'taxation',
									'amount',
									'setOutTime',
									'backTime',
									'startMileage',
									'endMileage',
									'oilCard',
									'subsidyProposer',
									'projectId',
									'projectCode',
									'attributionYear',
									'taskId',
									'taskDescription',
									'days',
									'feeType',
									'transportMode',
									'isSpecial',
									'untaxedAmount',
									'remark',
									'departurePlace',
									'targetPlace',
									'key',
									'selfDriving',
									'selfDrivingMode',
									'mileage',
									'subsidyUnitPrice',
								]),
							}
						}),
					})
					var _this = this
					if (response.success) {
						this.$refs.uToast.show({
							message: '提交成功',
							type: 'success',
							complete () {
								_this.onAudit()
							}
						})
						this.isSubmit = true
					}
				} finally {
					// error
				}
			},
			onAudit() {
			  if (!this.isSubmit) {
			    uni.showToast({
			      title: '请完善表单后审核',
			      icon: 'none',
			    })
			    return false
			  }
			  var that = this
			  uni.navigateTo({
			    url: '/pages/synergy/erpFinanceTravelReimbursementBillList' + `?item=${encodeURIComponent(JSON.stringify(this.dataForm).replace(/%/g, '%25'))}`,
			    events: {
			      // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
			      // acceptDataFromOpenedPage: function(data) {
			      // }
			    },
			    success: function (data) {
			      // 通过eventChannel向被打开页面传送数据
			      var params = {
			        nodeObj: encodeURIComponent(JSON.stringify(that.nodeObj).replace(/%/g, '%25')),
			        tabvalue: that.tabvalue,
			      }
			      data.eventChannel.emit('sendMessage', params)
			    },
			    fail: function (err) {
			      this.$refs.uToast.show({
			        message: '请联系管理员配置',
			        type: 'error',
			      })
			    },
			  })
			},
			resetMetaData() {
				const that = this
				//清除借款单字段
				that.$set(that.model, 'loanBillId', null)
				that.$set(that.model, 'outstandingAmount', null)
				that.$set(that.model, 'paymentAmount', null)
				that.$refs.form.clearValidate('loanBillId')
				//清空金额
				that.$set(that.model, 'reimbursementAmount', 0)
				that.getCurrentPaymentAmount(that.model.reimbursementAmount, that.model.chargedAmount)
				that.$set(that.model, 'kilometresAmount', 0)
				that.$set(that.model, 'thisAmount', 0)
			}
		},
		watch: {
			'model.companyId'(current, old) {
				if (old && current && old !== current) {
					this.backUpCompanyId = old
					this.resetMetaData()
				}
			},
			'model.teamId'(current, old) {
				if (old && current && old !== current) {
					this.backUpTeamId = old
					this.resetMetaData()
				}
			},
			'model.isRelProject'(current, old) {
				if (old && current && old !== current) {
					this.backUpIsRelProject = old
				}
			},
			/**
			 * 当公司和团队发生变化的时候清空借款单字段和金额
			 * @param {String} val
			 */
			backUpCompanyId(val) {
				if (this.model.isRelProject === '1') {
					this.resetMetaData()
				}
			},
			backUpTeamId(val) {
				if (this.model.isRelProject === '1') {
					this.resetMetaData()
				}
			},
			backUpIsRelProject(current, old) {},
		},
	}
</script>

<style scoped lang="scss">
	@import url('@/assets/inputStyle.scss');

	.trip-form-data {
		::v-deep {
			.u-form-item__body {
				padding-top: 2px;
				padding-bottom: 2px;
			}
		}
	}

	.checkbox-item {
		display: flex;
		align-items: center;
	}
</style>